/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ProtocolsTestGui.java
 *
 * Created on Sep 18, 2010, 3:54:50 PM
 */

package test.gui;

import com.flabot.remotestorage.auth.authenticator.Authenticator;
import com.flabot.remotestorage.auth.constants.AuthenticationConstants;
import com.flabot.remotestorage.auth.data.AmazonAuthenticationData;
import com.flabot.remotestorage.auth.data.DropboxAuthenticationData;
import com.flabot.remotestorage.factory.StorageServiceFactory;
import com.flabot.remotestorage.storageservice.StorageService;
import com.flabot.remotestorage.storageservice.StorageServiceData;
import com.flabot.remotestorage.storageservice.constants.StorageServiceConstants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JTextArea;

/**
 *
 * @author Kireta
 */
public class ProtocolsTestGui extends javax.swing.JFrame {

    /** Creates new form ProtocolsTestGui */
    public ProtocolsTestGui() {
        initComponents();
        //loadTextFile();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        StorageServiceComboBox = new javax.swing.JComboBox();
        AuthMethodComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        contentTextArea = new javax.swing.JTextArea();
        saveButton = new javax.swing.JButton();
        loadButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        StorageServiceComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StorageServiceComboBoxActionPerformed(evt);
            }
        });

        contentTextArea.setColumns(20);
        contentTextArea.setRows(5);
        jScrollPane1.setViewportView(contentTextArea);

        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        loadButton.setText("Load");
        loadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 515, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(StorageServiceComboBox, 0, 116, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(AuthMethodComboBox, 0, 116, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(loadButton)
                        .addGap(9, 9, 9)
                        .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(144, 144, 144))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(StorageServiceComboBox)
                        .addComponent(AuthMethodComboBox))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(saveButton, 0, 0, Short.MAX_VALUE)
                        .addComponent(loadButton)))
                .addContainerGap())
        );

        StorageServiceComboBox.addItem(StorageServiceConstants.S3_STORAGE_SERVICE);
        StorageServiceComboBox.addItem(StorageServiceConstants.DROPBOX_STORAGE_SERVICE);
        AuthMethodComboBox.addItem(AuthenticationConstants.AMAZON_AUTHENTICATION);
        AuthMethodComboBox.addItem(AuthenticationConstants.PASSWORD_AUTHENTICATION);
        AuthMethodComboBox.addItem(AuthenticationConstants.DROPBOX_AUTHENTICATION);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void StorageServiceComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StorageServiceComboBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_StorageServiceComboBoxActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    	if (((String) StorageServiceComboBox.getSelectedItem()).equals(StorageServiceConstants.S3_STORAGE_SERVICE)){
	        try {
	        	writeTextAreaToFile("cached.txt");
	        	
	        	AmazonAuthenticationData authData = new AmazonAuthenticationData();
	            authData.setAccessKey(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_ACCESS_KEY));
	            authData.setSecretKey(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_SECRET_KEY));
	            StorageServiceData storageData = new StorageServiceData();
	            storageData.setFileName(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_FILENAME));
	            storageData.setHost(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_BUCKET));
	            storageData.setPath(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_PATH));
	            storageData.setAuthData(authData);
	            StorageService service = StorageServiceFactory.instance.getStorageService((String) StorageServiceComboBox.getSelectedItem());
	            Authenticator authenticator = StorageServiceFactory.instance.getAuthenticator((String) AuthMethodComboBox.getSelectedItem());
	            service.connect(storageData, authenticator);
	            service.upload("cached.txt", storageData);
	    		service.disconnect();
	    		
	    		new File("cached.txt").delete();
	        } catch (Exception ex) {
	            Logger.getLogger(ProtocolsTestGui.class.getName()).log(Level.SEVERE, null, ex);
	        }
    	} else 		
    		if (((String) StorageServiceComboBox.getSelectedItem()).equals(StorageServiceConstants.DROPBOX_STORAGE_SERVICE)) {
    	    	try {
		        	writeTextAreaToFile("cached.txt");
		        	
		        	DropboxAuthenticationData authData = new DropboxAuthenticationData();
		            StorageServiceData storageData = new StorageServiceData();
		            storageData.setFileName(ProtocolsProperties.instance.getProperty(PropertiesConstants.TEST_FILENAME));
		            storageData.setHost(ProtocolsProperties.instance.getProperty(PropertiesConstants.DROPBOX_SERVER));
		            storageData.setPath(ProtocolsProperties.instance.getProperty(PropertiesConstants.DROPBOX_CONTENT_SERVER));
		            storageData.setAuthData(authData);
		            StorageService service = StorageServiceFactory.instance.getStorageService((String) StorageServiceComboBox.getSelectedItem());
		            Authenticator authenticator = StorageServiceFactory.instance.getAuthenticator((String) AuthMethodComboBox.getSelectedItem());
		            service.connect(storageData, authenticator);
		            service.upload("cached.txt", storageData);
		    		service.disconnect();
		    		
		    		new File("cached.txt").delete();
		        } catch (Exception ex) {
		            Logger.getLogger(ProtocolsTestGui.class.getName()).log(Level.SEVERE, null, ex);
		        }
    		}
    		
    }//GEN-LAST:event_saveButtonActionPerformed

    private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
        loadTextFile();
    }//GEN-LAST:event_loadButtonActionPerformed

    private void loadTextFile(){
    	if (((String) StorageServiceComboBox.getSelectedItem()).equals(StorageServiceConstants.S3_STORAGE_SERVICE)){
	    	try {
	    		AmazonAuthenticationData authData = new AmazonAuthenticationData();
	    		authData.setAccessKey(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_ACCESS_KEY));
	    		authData.setSecretKey(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_SECRET_KEY));
	    		StorageServiceData storageData = new StorageServiceData();
	    		storageData.setFileName(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_FILENAME));
	    		storageData.setHost(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_BUCKET));
	    		storageData.setPath(ProtocolsProperties.instance.getProperty(PropertiesConstants.S3_PATH));
	    		storageData.setAuthData(authData);
	    		StorageService service = StorageServiceFactory.instance.getStorageService((String) StorageServiceComboBox.getSelectedItem());
	    		Authenticator authenticator = StorageServiceFactory.instance.getAuthenticator((String) AuthMethodComboBox.getSelectedItem());
	    		service.connect(storageData, authenticator);
	    		service.download("remotefile.txt", storageData);
	    		service.disconnect();
	    		
	    		readFileToTextArea("remotefile.txt");    		
	    		new File("remotefile.txt").delete();    	
	    		
	    	}catch (Exception ex) {
	    		Logger.getLogger(ProtocolsTestGui.class.getName()).log(Level.SEVERE, null, ex);
	    	}
    	} else 
    		if (((String) StorageServiceComboBox.getSelectedItem()).equals(StorageServiceConstants.DROPBOX_STORAGE_SERVICE)) {
    	    	try {
    	    		DropboxAuthenticationData authData = new DropboxAuthenticationData();
    	    		StorageServiceData storageData = new StorageServiceData();
    	    		storageData.setFileName(ProtocolsProperties.instance.getProperty(PropertiesConstants.TEST_FILENAME));
    	    		storageData.setHost(ProtocolsProperties.instance.getProperty(PropertiesConstants.DROPBOX_SERVER));
    	    		storageData.setPath(ProtocolsProperties.instance.getProperty(PropertiesConstants.DROPBOX_CONTENT_SERVER));
    	    		storageData.setAuthData(authData);
    	    		StorageService service = StorageServiceFactory.instance.getStorageService((String) StorageServiceComboBox.getSelectedItem());
    	    		Authenticator authenticator = StorageServiceFactory.instance.getAuthenticator((String) AuthMethodComboBox.getSelectedItem());
    	    		service.connect(storageData, authenticator);
    	    		service.download("cached.txt", storageData);
    	    		service.disconnect();
    	    		
    	    		readFileToTextArea("cached.txt");    		
    	    		new File("cached.txt").delete();    	
    	    		
    	    	}catch (Exception ex) {
    	    		Logger.getLogger(ProtocolsTestGui.class.getName()).log(Level.SEVERE, null, ex);
    	    	}
    		}
    }
    
    private void writeTextAreaToFile(String filename) throws IOException {

    	FileWriter outFile = null;   
    	PrintWriter pr = null;
    	try{
    		outFile = new FileWriter(filename);
            pr = new PrintWriter(outFile);
        	String[] lines = contentTextArea.getText().split("\n");
        	for(int i = 0;i < lines.length;i++) {
        		pr.println(lines[i]);
        	} 
    	}catch(IOException e){
    		e.printStackTrace();
    		throw e;
    	} finally {
    		if(outFile != null) {
    			outFile.close();
    		}
    		if(pr != null) {
    			pr.close();
    		}
    	}
    }
    
    private void readFileToTextArea(String filename) throws IOException {
    	FileReader fr = null;
    	try {
    		fr = new FileReader(filename);
    		contentTextArea.read(fr, null);
    		fr.close();
    	} catch (IOException e) {
    		e.printStackTrace();
    		throw e;
    	} finally {
    		if(fr != null) {
    			fr.close();
    		}
    	}
    }

	/**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ProtocolsTestGui().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox AuthMethodComboBox;
    private javax.swing.JComboBox StorageServiceComboBox;
    private javax.swing.JTextArea contentTextArea;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton loadButton;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables

}
